import uuid
from django import forms
from utils.centent.cos import upload_img

from api import models
# 编辑(为改变)
from django.db.models.fields.files import FieldFile
# 上传
from django.core.files.uploadedfile import InMemoryUploadedFile


class BootStrapForm:
    except_bootstrap_styles = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if name in self.except_bootstrap_styles:
                continue
            old_class = field.widget.attrs.get('class', "")
            field.widget.attrs['class'] = '{} form-control'.format(old_class)
            field.widget.attrs['placeholder'] = f'请输入{field.label}'


class AuctionList(BootStrapForm, forms.ModelForm):
    """拍卖场列表"""
    except_bootstrap_styles = ['cover']

    # cover = forms.CharField(label='图片')

    class Meta:
        model = models.Auction  # 对应的Model中的类
        exclude = ['create_time', 'look_count', 'bid_count', 'goods_count', 'total_price', 'video', 'is_operation']

    def clean(self):
        cover_file_object = self.cleaned_data.get('cover')
        # 判断是没有传图片 or 编辑(为修改)
        if not cover_file_object or isinstance(cover_file_object, FieldFile):
            return self.cleaned_data
        # print('obj', cover_file_object)
        # 获取上传的文件名称，
        # 进行拼接，
        ext = cover_file_object.name.rsplit('.', maxsplit=1)[-1]
        file_name = "{0}.{1}".format(str(uuid.uuid4()), ext)
        # 调用上传文件，上传到cos
        result_url = upload_img(Bucket='admin-1305448189', region='ap-chengdu', Body=cover_file_object,
                                Key=file_name)
        # 给cover字段添加路由
        self.cleaned_data['cover'] = result_url
        # print('url', result_url)
        return self.cleaned_data


class AuctionItemAdd(BootStrapForm, forms.ModelForm):
    """csdn更新"""
    except_bootstrap_styles = ['cover']

    class Meta:
        model = models.AuctionItem  # 对应的Model中的类
        fields = ['title', 'cover', 'start_price', 'reserve_price', 'highest_price', 'deposit', 'unit']

    def clean(self):
        cover_file_object = self.cleaned_data.get('cover')
        # print('cover', cover_file_object)
        # 判断是没有传图片 or 编辑(为修改)
        if not cover_file_object or isinstance(cover_file_object, FieldFile):
            return self.cleaned_data
        # print('obj', cover_file_object)
        # 获取上传的文件名称，
        # 进行拼接，
        ext = cover_file_object.name.rsplit('.', maxsplit=1)[-1]
        file_name = "{0}.{1}".format(str(uuid.uuid4()), ext)
        # 调用上传文件，上传到cos
        result_url = upload_img(Bucket='admin-1305448189', region='ap-chengdu', Body=cover_file_object,
                                Key=file_name)
        # 给cover字段添加路由
        self.cleaned_data['cover'] = result_url
        # print('url', result_url)
        return self.cleaned_data


class CouponList(BootStrapForm, forms.ModelForm):
    except_bootstrap_styles = ['cover']

    # cover = forms.CharField(label='图片')

    class Meta:
        model = models.CouponStrength  # 对应的Model中的类
        exclude = ['create_time', 'is_show', 'is_delete', 'create_time', 'update_time']

    def clean(self):
        cover_file_object = self.cleaned_data.get('cover')
        # 判断是没有传图片 or 编辑(为修改)
        if not cover_file_object or isinstance(cover_file_object, FieldFile):
            return self.cleaned_data
        # print('obj', cover_file_object)
        # 获取上传的文件名称，
        # 进行拼接，
        ext = cover_file_object.name.rsplit('.', maxsplit=1)[-1]
        file_name = "{0}.{1}".format(str(uuid.uuid4()), ext)
        # 调用上传文件，上传到cos
        result_url = upload_img(Bucket='admin-1305448189', region='ap-chengdu', Body=cover_file_object,
                                Key=file_name)
        # 给cover字段添加路由
        self.cleaned_data['cover'] = result_url
        # self.cleaned_data['cover'] = 'result_url'
        return self.cleaned_data


class CouponTitleForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.CouponTitle
        fields = ['title']
